const { table } = require('console');
var express = require('express');
var router = express.Router();
var fs = require('fs');

function getPathByMap(tableName) {
  let folderPath = 'C:/Users/tommy/Desktop';
  return folderPath;
}

function getRetObj(param) {
  return {
    success: true,
    code: 200,
    msg: '成功',
    data: param,
  };
}

function sortFile(resData) {
  const listDir = resData
    .filter(item => {
      return item.isDirectory;
    })
    .sort((a, b) => {
      return a > b;
    });
  const listFile = resData
    .filter(item => {
      return item.isFile;
    })
    .sort((a, b) => {
      return a > b;
    });
  return listDir.concat(listFile);
}

/**
 * [root] 查询所有
 */
router.get('/root', function (req, res) {
  let tableName = req.params.tableName;
  const folderPath = getPathByMap(tableName);

  // 查询列表，读取文件
  const nameList = fs.readdirSync(folderPath, { withFileTypes: true });

  const resData = nameList.map(item => {
    return {
      name: item.name,
      parentPath: item.parentPath,
      isDirectory: item.isDirectory(),
      isFile: item.isFile(),
      // isFIFO: item.isFIFO(),
      // isSocket: item.isSocket(),
      // isBlockDevice: item.isBlockDevice(),
      // isSymbolicLink: item.isSymbolicLink(),
      // isCharacterDevice: item.isCharacterDevice(),
    };
  });

  res.send(getRetObj(sortFile(resData)));
});
/**
 * [folder] 查询所有
 */
router.get('/folder', function (req, res) {
  let path = req.query.path;
  let name = req.query.name;
  const folderPath = getPathByMap();

  const nameList = fs.readdirSync(folderPath + '/' + name, { withFileTypes: true });

  const resData = nameList.map(item => {
    return {
      name: item.name,
      parentPath: item.parentPath,
      isDirectory: item.isDirectory(),
      isFile: item.isFile(),
    };
  });

  res.send(getRetObj(sortFile(resData)));
});
/**
 * [stat] 单个文件状态
 */
router.get('/stat', function (req, res) {
  let path = req.query.path;
  let name = req.query.name;
  const folderPath = getPathByMap();

  fs.stat(folderPath + '/' + name, (error, stats) => {
    const resData = {
      name: name,
      parentPath: path,
      isDirectory: false,
      isFile: true,
      type: '文件',
      size: stats.size,
      lastModified: stats.mtime,
    };

    res.send(getRetObj(resData));
  });
});

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;
